package com.chuangshu.chuangshuteam.controller;


import com.alibaba.excel.EasyExcel;
import com.chuangshu.chuangshuteam.annotation.RequiresRoles;
import com.chuangshu.chuangshuteam.dto.AssessmentPassListDto;
import com.chuangshu.chuangshuteam.dto.Result;
import com.chuangshu.chuangshuteam.entity.UserExportData;
import com.chuangshu.chuangshuteam.service.AssessmentPassListsService;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;


@Slf4j
@RestController
@RequestMapping("/assessment-pass-lists")
public class AssessmentPassListsController {
    @Autowired
    private AssessmentPassListsService assessmentPassListsService;

    /**
     * 分页查询通过列表
     * @param page 页码，默认为1
     * @param pageSize 每页大小，默认为10
     * @return 分页结果
     */
    @GetMapping("/list")
    public Result list(@RequestParam(defaultValue = "1") Integer page,
                       @RequestParam(defaultValue = "10") Integer pageSize) {
        log.info("分页查询通过列表，页码: {}, 每页大小: {}", page, pageSize);
        Result result = assessmentPassListsService.getByPage(page, pageSize);
        return result;
    }

    /**
     * 根据ID查询通过列表详细信息
     * @param id 通过列表ID
     * @return 详细信息
     */
    @GetMapping("/detail/{id}")
    public Result detail(@PathVariable Long id) {
        log.info("根据ID查询通过列表详情: {}", id);
        AssessmentPassListDto passList = assessmentPassListsService.getById(id);
        if (passList == null) {
            return Result.fail("通过列表记录不存在");
        }
        return Result.ok(passList);
    }
    @RequiresRoles("member")
    @GetMapping("/export/users")
    public void exportUsers(HttpServletResponse response) throws IOException {
        // 1. 设置响应头
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding(StandardCharsets.UTF_8.name());
        // 防止中文文件名乱码
        String fileName = URLEncoder.encode("面试通过信息表", StandardCharsets.UTF_8).replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");

        // 2. 准备要导出的数据（这里是模拟数据，实际应从数据库查询）
        List<UserExportData> dataList = assessmentPassListsService.getPassList();

        // 3. 调用 EasyExcel 的 API 进行导出
        EasyExcel.write(response.getOutputStream(), UserExportData.class)
                .sheet("用户列表") // 指定 sheet 的名称
                .doWrite(dataList); // 写入数据
    }
}

